import { Injectable } from '@nestjs/common';
import { Like, Repository } from 'typeorm';
import { note } from './entities/note.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateNoteDto } from './dto/create-note.dto';
import { UpdateNoteDto } from './dto/update-note.dto';
import { Utils } from '../common/utils';

type IqueryWrapper = {
  order?: {
    createTime?: {
      direction: 'asc' | 'desc';
    };
    modifyTime?: {
      direction: 'asc' | 'desc';
    };
  };
  [key: string]: any;
};

@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(note)
    private readonly noteRepository: Repository<note>,
    private readonly utils: Utils,
  ) {}

  // 新建笔记
  async createNote(createNoteDto: CreateNoteDto) {
    const newNote = new note();
    newNote.author = createNoteDto.author;
    newNote.title = createNoteDto.title;
    newNote.content = createNoteDto.content;
    newNote.createTime = this.utils.getNowDate();
    newNote.modifyTime = this.utils.getNowDate();

    const body = await this.noteRepository.save(newNote);
    return { body };
  }

  // 编辑笔记
  async updateNote(updateNoteDto: UpdateNoteDto) {
    const newNote = new note();
    newNote.id = updateNoteDto.id;
    newNote.title = updateNoteDto.title;
    newNote.content = updateNoteDto.content;
    newNote.modifyTime = this.utils.getNowDate();

    const body = await this.noteRepository.update(newNote.id, newNote);
    return { body };
  }

  // 删除笔记
  async deleteNote(id: string) {
    const newNote = new note();
    newNote.id = id;
    const body = await this.noteRepository.remove(newNote);
    console.log(id, body, newNote);

    return { body };
  }

  // 获取笔记列表
  async getNoteList(query) {
    const { title = '', author = '', order = '' } = query?.searchContent;
    const orderKey: 'createTime' | 'modifyTime' =
      order.split(':')[0] || 'modifyTime';
    const orderValue: 'asc' | 'desc' = order.split(':')[1] || 'desc';
    const queryWrapper: IqueryWrapper = {
      where: {
        title: Like(`%${title}%`),
        author: Like(`%${author}%`),
      },
      order: {
        [orderKey]: {
          direction: orderValue,
        },
      },
      skip: query.pageSize * (query.pageNo - 1),
      take: query.pageSize,
    };
    const list = await this.noteRepository.find(queryWrapper);
    const total = await this.noteRepository.count(queryWrapper);
    return { body: { list, total } };
  }

  // 获取笔记详情
  async getNoteDetails(id: string) {
    const queryWrapper = {
      where: {
        id,
      },
    };
    const list = await this.noteRepository.find(queryWrapper);

    return { body: { ...list[0] } };
  }
}
